package dir

import (
	"errors"
	"fmt"
	"hft/Database/admin/file"
	"hft/Http/Models/response/admin_res"
	"hft/Http/Services/base"
	dirdao "hft/Http/Services/dir/dir_dao"
	"hft/e"
	"hft/global"
	"hft/tools"
	"strings"
)

type Dir struct{}

// 获取目录
func (*Dir) List(claims tools.BaseClaims, pid int) (list []*admin_res.Dir, err error) {

	account, err := base.FindAccount(claims, global.OC_DB)

	if err != nil {
		return nil, err
	}

	var newList = make([]*file.Dir, 0)
	global.OC_DB.Model(&file.Dir{}).Where("account_id = ?", account.ID).Where("link LIKE ?", ",%%").Find(&newList)

	var tree = make([]*admin_res.Dir, 0)

	for _, v := range newList {
		var is_leaf bool
		var level = strings.Split(v.Link, ",")
		if len(level) >= 5 {
			is_leaf = true
		} else {
			is_leaf = false
		}
		tree = append(tree, &admin_res.Dir{Name: v.Name, PID: v.PID, ID: v.ID, IsLeaf: is_leaf})
	}

	return tree, nil
}

// 创建目录
func (*Dir) Add(claims tools.BaseClaims, data *file.Dir) (err error) {

	account, err := base.FindAccount(claims, global.OC_DB)

	if err != nil {
		return err
	}

	link, err := dirdao.FindPDir(int(account.ID), int(data.PID), global.OC_DB)

	if err != nil {
		return err
	}

	// 最多二级目录
	if len(strings.Split(link, ",")) >= 5 {
		return errors.New("最多只能创建三级目录")
	}

	data.Link = fmt.Sprintf("%v%v,", link, data.PID)
	var dir = &file.Dir{
		AccountID: account.ID,
		Name:      data.Name,
		Link:      data.Link,
		PID:       data.PID,
	}

	err = global.OC_DB.Create(&dir).Error

	if err != nil {
		return errors.New(e.ErrorInfo)
	}

	return nil
}

func (*Dir) Edit(claims tools.BaseClaims, data *file.Dir) (err error) {
	account, err := base.FindAccount(claims, global.OC_DB)

	if err != nil {
		return err
	}

	err = global.OC_DB.Model(&file.Dir{}).Where("account_id = ?", account.ID).Where("id = ?", data.PID).Updates(map[string]interface{}{
		"name": data.Name,
	}).Error

	if err != nil {
		return errors.New(e.DirNotExist)
	}

	return nil
}

func (*Dir) Delete(claims tools.BaseClaims, id int) (err error) {

	account, err := base.FindAccount(claims, global.OC_DB)

	if err != nil {
		return err
	}

	err = global.OC_DB.Model(&file.Dir{}).Where("account_id = ?", account.ID).Unscoped().Delete(&file.Dir{}, id).Error

	if err != nil {
		return errors.New(e.DeleteFail)
	}
	return nil

}

var DirService = new(Dir)
